import Container from '@/components/Container'
import BlogPost from '@/components/BlogPost'
import Pagination from '@/components/Pagination'
import { getAllPosts } from '@/lib/notion'
import SITE from '@/site.config'

const Page = ({ postsToShow, page, showNext }) => {
  return (
    <Container>
      <div className="grid grid-cols-3 gap-6">
        {postsToShow &&
          postsToShow.map((post) => <BlogPost key={post.id} post={post} />)}
      </div>
      <Pagination page={page} showNext={showNext} />
    </Container>
  );
}

export async function getStaticProps(context) {
  const { page } = context.params // Get Current Page No.
  let posts = await getAllPosts()
  posts = posts.filter(
    post => post.status[0] === 'Published' && post.type[0] === 'Post'
  )
  const postsToShow = posts.slice(
   SITE.postsPerPage * (page - 1),
   SITE.postsPerPage * page
  )
  const totalPosts = posts.length
  const showNext = page *SITE.postsPerPage < totalPosts
  return {
    props: {
      page, // Current Page
      postsToShow,
      showNext
    },
    revalidate: 1
  }
}

export async function getStaticPaths() {
  let posts = await getAllPosts()
  posts = posts.filter(
    post => post.status[0] === 'Published' && post.type[0] === 'Post'
  )
  const totalPosts = posts.length
  const totalPages = Math.ceil(totalPosts /SITE.postsPerPage)
  return {
    // remove first page, we 're not gonna handle that.
    paths: Array.from({ length: totalPages - 1 }, (_, i) => ({
      params: { page: '' + (i + 2) }
    })),
    fallback: true
  }
}

export default Page
